
// 获取应用实例
const app = getApp()
import service from '../../utils/request'
import { storeBindingsBehavior, createStoreBindings } from 'mobx-miniprogram-bindings'
import { store } from '../../store/store'
import { formatTime, formatDate } from '../../utils/util'
Page({
  data: {
    option1: [
      { text: '选择城市', value: 0 },
      { text: '成都市', value: 1 },
    ],
    isVip: false,
    currenSite: '',
    token: wx.getStorageSync('token'),
    dictLevel: 1,
    isDict: app.globalData.isFirstViewPatch,
    showPriceList:false,
    soketUrl:"wss://wxsocket.ztkuaichong.com:3027?token="+wx.getStorageSync('token'),
    // soketUrl: "wss://38449129qz.qicp.vip/websocket/push?token="+wx.getStorageSync('token'),
    userPhone: app.globalData.userPhone,
    baseUrl: app.data.url,
    imageurl: app.data.imageurl,
    isShowAdvise: app.globalData.isShowAdvise,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    canIUseGetUserProfile: false,
    canIUseOpenData: wx.canIUse('open-data.type.userAvatarUrl') && wx.canIUse('open-data.type.userNickName'), // 如需尝试获取用户信息可改为false
    bannerList: [],
    isShowPercent: false, //是否展示充电进度
    latitude: '',
    longitude: '',
    siteList: [],
    topTage: 100,
    interval:'',
    oid:'',
    page: 1,
    nextPage: true,
    isReach: false, //是否正在下拉刷刷新中
    order: {
      "chargeTime":0,
      "comboDiscount":0.00,
      "createTime":"2022-01-10 15:27:58",
      "current":0.0,
      "discount":0.00,
      "electricity":0.0,
      "gunSn":"0100001000000101",
      "oid":"ZTWX01101527583919",
      "plate":"川ADF1245",
      "plateState":4,
      "power":0.0,
      "powerPrice":0.00,
      "servicePrice":0.00,
      "siteId":1,
      "siteName":"成华测试站点",
      "soc":0.0,
      "state":1,
      "total":0.00,
      "voltage":0.0
    },
    
  },
    
  //下一个指导页
  nextDic(){
    let num = this.data.dictLevel +1
    let isDict = true
    if(num >2){
      isDict = false
    }
    this.setData({
      dictLevel: num,
      isDict: isDict
    })
  },
  userPile(){
    wx.navigateTo({
      url: '/package1/pages/person/person',
    })
  },
  // 事件处理函数
  bindViewTap() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onClose(){
    this.setData({
      showPriceList: false
    })
  },
  //费率列表
  handleTap(e){
    this.setData({
      showPriceList: true,
      currenSite: e.currentTarget.dataset.id
    })
    console.log('currenSite',this.data.currenSite)
  },
  adviseMove(e){
    // console.log(e)
    return false
  },
  getBanner() {
    wx.request({
      url: this.data.baseUrl + '/banner/list',
      method: "GET",
      data: {},
      success: (res) => {
        console.log('banner', res)
        let data = res.data.list
        data.map(item => {
          item.image = this.data.imageurl + item.image
          return item
        })
        this.setData({
          bannerList: data
        })
        console.log('bannerList', data)
      }
    })
  },

  goCate(e) {
    console.log(e)
    wx.navigateTo({
      url: '/pages/shoplist/shoplist?ids=' + e.currentTarget.dataset.ids + '&nick=' + e.currentTarget.dataset.nick,
    })
  },
  toBalance() {
    if(!wx.getStorageSync('token')){
      this.isLogin()
    }
    wx.navigateTo({
      url: '/subpage/pages/balance/balance',
    })
  },
  topushcode() {
    wx.navigateTo({
      url: '/subpage/pages/pushcode/pushcode',
    })
  },
  //扫码
  userScen() {
    // 允许从相机和相册扫码
    wx.scanCode({
      success(res) {
        console.log(res)
        let sn = res.result;
        let index = sn.lastIndexOf("\=");
        sn = sn.substring(index + 1, sn.length);
        console.log(res.result)
        wx.navigateTo({
          url: '/subpage/pages/charge/charge?sn=' + sn,
        })
      }
    })
  },
  isLogin () {
    wx.navigateTo({
			url: "/subpage/pages/login/login"
		})
  },
  onLoad() {
    this.storeBindings = createStoreBindings(this, {
      store,
      actions: ['updateActives'],
    })
    this.nearSite()
    if(wx.getStorageSync('advise')){
      let advise = JSON.parse(wx.getStorageSync('advise'))
      advise.map(item => {
        item.image = this.data.baseUrl+item.image
      })
      this.setData({
        adviseList: advise
      })
    }
    let that = this
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      })
    };
    this.getBanner()
    // 在页面中定义插屏广告
    // if(wx.getStorageSync('token') && wx.getStorageSync('userPhone')===true){
    //   this.chargeOrder()
    // }
  },
  onShareAppMessage: function () {
    
  },
  inSoket(){
    let that = this
    wx.connectSocket({
      url: that.data.soketUrl,
    })
    wx.onSocketOpen((res) => {
      console.log('检查到soket连接成功，清除定时', res);
      if(!that.data.interval){
        clearInterval(that.data.interval)
      }
    })
     //接受数据
     wx.onSocketMessage((data) => {
      console.log('soket成功返回',data);
      this.setChar(data)
    })
    
  },

  onShow() {
    this.updateActives(1)
    console.log('切前台')
    let that = this;
    this.setData({
      token: wx.getStorageSync('token')
    })
    if(this.data.siteList.length < 1 || wx.getStorageSync('token')){
      this.setData({
        page: 1
      })
      if(!this.data.latitude){
        this.nearSite()
      }else{
        this.getSite()
      }
      
    }
    
    if (!wx.getStorageSync('token')){
      // this.isLogin()
      this.setData({isVip: false})
    }else{
      that.getusers()
    }
    that.inSoket()
    if( wx.getStorageSync('token') && wx.getStorageSync('userPhone') ===true){
      console.log('充电进度')
      this.chargeOrder()
    }
  },
  onHide() {
    console.log('切后台')
    let that = this
    wx.closeSocket({
      complete:() => {
        console.log('index onHide测试hide关闭soket，删除定时器')
        clearInterval(that.data.interval)
      }
     })
  },
  onUnload: function () {
    this.storeBindings.destroyStoreBindings()
    console.log('卸载关闭socket')
    if(this.data.interval){
      console.log('卸载清楚定时器')
      clearInterval(this.data.interval)
    }
    wx.closeSocket({
      complete:() => {
        console.log('测试onUnload关闭soket，删除定时器')
      }
     })
    // wx.switchTab({
    //    url: '/pages/scen/scen',
    // })
  },
   getUserProfile(e) {
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log(res)
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    })
  },
  getUserInfo(e) {
    // 不推荐使用getUserInfo获取用户信息，预计自2021年4月13日起，getUserInfo将不再弹出弹窗，并直接返回匿名的用户个人信息
    console.log(e)
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },


  phoneCall(){
    wx.makePhoneCall({
      phoneNumber: '17381912715' 
    })
  },
  //跳转
  toPlatfrom() {
    wx.navigateTo({
      url: '/subpage/pages/platfrom/platfrom',
    })
  },
  // 地图查询
  toCombo() {
    wx.navigateTo({
      url: '/subpage/pages/combo/combo',
    })
  },
  //站点详情
  gosite(event){
    wx.navigateTo({
      url: '/subpage/pages/sitedetail/sitedetail?id='+event.currentTarget.dataset.id+'&parking='+event.currentTarget.dataset.parking,
    })
  },
  // 站点查询
  tpSiteList() {
    wx.navigateTo({
      url: '/subpage/pages/sitelist/sitelist',
    })
  },
  //取消弹出
  quxiao() {
    //淡出
    this.animate('#waitout',[
      {opacity:0.5,height:'500rpx',width: '60%'},
      {opacity:0.3,height:'400rpx',width: '50%'},
      // {opacity:0.2},
    ],30,function(){
      this.setData({
        isShowAdvise: false
      })
    }.bind(this))

   
  },
  tocarBrand() {
    if (!this.data.token) {
      this.isLogin();
      return;
    }
    wx.navigateTo({
      url: "/subpage/pages/carbeand/carbeand"
    })
  },
   //获取个人信息
   getusers(){
     let that = this
    let data = service('GET','/user/info',{}).then( res => {
      console.log('我获取了我的头像',res)
      if( res.data.code !==0){
        if(res.data.code ==266 || res.data.code == 414){
          that.setData({
            isVip: false
          })
        }
        if(res.data.code ==414){
          wx.showToast({
            title: '登录信息过期，请重新登录',
            icon:'none'
          })
         
          // wx.setStorageSync('userPhone',false)
          wx.setStorageSync('userinfo','')
          wx.setStorageSync('token','')
          this.setData({
            token: ""
          })
          // wx.navigateTo({
          //   url: '/subpage/pages/login/login',
          // })
         return
        }else{
          // wx.setStorageSync('userPhone',false)
          wx.setStorageSync('userinfo','')
          wx.setStorageSync('token','')
          this.setData({
            token: ""
          })
        }
      }else{
        that.setData({
          isVip: res.data.user.isVip
        })
      }
       
      
    })
  },
  //查看进行中的订单
  goOrder() {
    wx.navigateTo({
      url: '/subpage/pages/detail/detail?oid='+this.data.order.oid,
    })
  },
  //正在充电的订单
  chargeOrder() {
    let that = this
    let result = service('GET', '/order/charging').then(res => {
      console.log('正在充电订单', res)
      if (res.data.code == 0) {
        let order = res.data.order
        let surplusTime = order.surplusTime ? parseInt(order.surplusTime/60) :0
        order.surHours = Math.floor(surplusTime/60) < 10 ? '0'+Math.floor(surplusTime/60) : ''+Math.floor(surplusTime/60)
        let surMin = surplusTime - (Math.floor(surplusTime/60)*60)
        order.surMin = surMin < 10 ? '0'+surMin : ''+surMin
        that.setData({
          isShowPercent: true,
          order:res.data.order,
        })
        wx.onSocketClose(function (resS) {
          console.log('onSocketClose！，发起定时器detail,但不重复发起')
         if(!that.data.interval){
          console.log('第一次发起定时器')
          that.setIntevel()
         }
        })
         //接受数据
        wx.onSocketMessage((data) => {
          console.log('charOrder中检测soket成功返回',data);
          //如果type ！=2 }|| type !=3 停止soket
          clearInterval(that.data.interval)
          that.setChar(data)
        })
        //连接失败
        // wx.onSocketError(function() {
        //   console.log('websocket连接失败！');
        // })
      }else{
        console.log('清除定时器，当前无充电订单')
        if(this.data.interval){
          clearInterval(this.data.interval)
        }
        that.setData({
          isShowPercent: false,
        })
      }
    })
  },
  setIntevel(){
    let that = this
    that.data.interval = setInterval(function() {
      console.log('试图连接soket')
      wx.connectSocket({
        url: that.data.soketUrl,
      })
      that.chargeOrder()
       console.log("执行30秒定时----------------------------------------------------")
     }, 30000)
  },
  //设置电量
  setChar(data){
    let result = JSON.parse(data.data)
    console.log('socket赋值', result)
    this.setData({
      isShowPercent: true,
      order: result
    })
    return
    if(result.type !=2 && result.type !=3){
      console.log('因为状态不在充电关闭soket')
      wx.closeSocket()
      this.setData({
        isShowPercent: true,
      })
    }
  },
  //附近站点
  nearSite() {
    let that = this
    wx.getLocation({
      type: 'gcj02',
      success: function (res) {
        console.log('我访问了地图', res)
        that.setData({
          latitude: res.latitude,
          longitude: res.longitude,
        })
        that.getSite()
      },
    })
  },
  getSite(resh){
    console.log('加载siteList')
    let that = this
    let res1 = service('POST', '/iot/site',{
      lat: that.data.latitude,
      lng: that.data.longitude,
      page: this.data.page,
      distance: 400000
    }).then(res => {
      console.log('siteList', res)
      if (res.data.code == 0) {
        let site = res.data.page.list
        let site1 = site.map(item => {
          if (item.distance) {
            item.distance = (item.distance / 1000).toFixed(1)
          }
          if(item.discount){
            item.discount = (item.discount).toFixed(3)+''
          }
          return item
        })
        let dataList = []
        if(resh =='bottom'){
          dataList = [...that.data.siteList, ...site1]
        }else{
          dataList = site1
        }
        that.setData({
          nextPage: res.data.page.hasNext,
          isReach: !res.data.page.hasNext,
          siteList: dataList
        })
        if(resh){
          wx.stopPullDownRefresh()
        }
      }
    })
  
  },
  //导航
  navi_btn: function (e) {
    console.log('导航', e)
    let lng = e.target.dataset.lng;
    let lat = e.target.dataset.lat;
    // var _gcj02 = util.bd09Togcj02(lng, lat);
    let address = e.target.dataset.address;
    wx.getLocation({
      type: 'gcj02',
      success: function (res) {
        wx.openLocation({
          latitude:Number(lat),
          longitude: Number(lng),
          name: address,
          scale: 16, //缩放比例为18
        })
      },
    })
  },
  goAdvise(event){
    console.log(event)
    if(event.target.dataset.url){
      wx.navigateTo({
        url: event.target.dataset.url,
      })
    }
  },

  //下拉刷新
  onPullDownRefresh() {
    console.log('下拉刷新')
    this.setData({
      page: 1,
    })
    this.getSite('resh')
  },
    /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    console.log('onReachBottom')
    if(this.data.isReach){
      return false
    }
    this.setData({
      page: this.data.page + 1,
      isReach: true
    })
    console.log('下一页', this.data.isReach)
    this.getSite('bottom')
  },
})